<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="close()"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="来往单位" prop="organName">
        <el-select
          v-model="dataForm.organName"
          placeholder="请选择"
          @change="change1"
        >
          <el-option
            v-for="item in options1"
            :key="item.id"
            :label="item.supplier"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="经手人" prop="handsPersonName">
        <el-select
          v-model="dataForm.handsPersonName"
          placeholder="请选择"
          @change="change2"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="单据日期"
        prop="billTime"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-date-picker
          v-model="dataForm.billTime"
          type="datetime"
          placeholder="选择日期时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="单据编号"
        prop="billNo"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          v-model="dataForm.billNo"
          placeholder="单据编号"
          :readonly="true"
        ></el-input>
      </el-form-item>
    </el-form>
    <el-form
      :model="dataList"
      :rules="dataRule1"
      ref="dataList"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="收入项目" prop="InOutItemName">
        <el-select
          v-model="dataList.InOutItemName"
          placeholder="请选择"
          @change="change3($event)"
        >
          <el-option
            v-for="item in options2"
            :key="item.Id"
            :label="item.InOutItemName"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="金额" prop="EachAmount">
        <el-input
          v-model="dataList.EachAmount"
          placeholder="金额"
          onkeyup="value=value.replace(/[^\d^\.]+/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.')"
        ></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="Remark">
        <el-input v-model="dataList.Remark" placeholder="备注"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :disabled="btnstatus"
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from "@/utils/validate";
export default {
  data() {
    return {
      btnstatus: false,
      parentValue: [],
      value2: "",
      options1: [],
      options: [],
      options2: [],
      value: "",
      value: "",
      value6: "",
      visible: false,
      roleList: [],
      dataForm: {
        id: 0,
        organName: "",
        handsPersonName: "",
        billTimeStr: "",
        billNo: "",
        Price: "",
        Remark: "",
      },
      dataList: {
        InOutItemName: "",
        InOutItemId: "",
        EachAmount: "",
        Remark: "",
        id: "",
      },
      dataRule: {
        organName: [
          { required: true, message: "来往单位不能为空", trigger: "change" },
        ],
        handsPersonName: [
          { required: true, message: "经手人不能为空", trigger: "change" },
        ],
        billTimeStr: [
          { required: true, message: "单据日期不能为空", trigger: "change" },
        ],
        billNo: [
          { required: true, message: "收入项目不能为空", trigger: "change" },
        ],
      },
      dataRule1: {
        InOutItemName: [
          { required: true, message: "收入项目不能为空", trigger: "change" },
        ],
        EachAmount: [
          { required: true, message: "金额不能为空", trigger: "change" },
        ],
      },
      AccountId: "",
      InOutItemId: "",
      OrganId: "",
      HandsPersonId: "",
      id: "",
    };
  },
  methods: {
    change1(id) {
      // console.log(id);
      this.OrganId = id;
    },
    change2(id) {
      // console.log(id);
      this.HandsPersonId = id;
    },
    change3(item) {
      console.log(item);
      this.InOutItemId = item.Id;
      this.dataList.InOutItemName = item.InOutItemName;
    },
    handleChange(value) {
      console.log(value);
    },
    init(index, id, pageIndex, pageSize, userID, beginTime, endTime) {
      // console.log(index, id, pageIndex, pageSize, userID, beginTime, endTime);
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.$refs["dataList"].resetFields();
        let str = `{"supplier":"","type":"客户","phonenum":"","telephone":"","description":""}`;
        var search = encodeURIComponent(str);
        this.$http({
          url: this.$http.adornUrl(`/supplier/list?search=${search}`),
          method: "get",
          params: this.$http.adornParams({
            currentPage: 1,
            pageSize: 10,
          }),
        }).then(({ data }) => {
          console.log(data.data);
          if (data && data.code === 0) {
            this.options1 = data.data;
          }
        });
        let str1 = `{"name":"","type":"","remark":""}`;
        var search = encodeURIComponent(str1);
        this.$http({
          url: this.$http.adornUrl(`/inOutItem/findBySelect?type=in`),
          method: "get",
        }).then(({ data }) => {
          console.log(data);
          this.options2 = data;
          // if (data && data.code === 0) {
          //   this.options2 = data;
          // }
        });
        let str2 = `{"name":"","type":""}`;
        var search = encodeURIComponent(str2);
        this.$http({
          url: this.$http.adornUrl(`/person/list?search=${search}`),
          method: "get",
          params: this.$http.adornParams({
            currentPage: 1,
            pageSize: 10,
          }),
        }).then(({ data }) => {
          // console.log(data);
          this.options = data.data.list;
        });
        if (this.dataForm.id) {
          // console.log(this.dataForm.id);
          let type = "收入";
          let roleType = "全部数据";
          let str = `{"type":"${type}","roleType":"${roleType}","billNo":"${userID}","beginTime":"${beginTime}","endTime":"${endTime}"}`;
          var search = encodeURIComponent(str);
          this.$http({
            url: this.$http.adornUrl(`/accountHead/list?search=${search}`),
            method: "get",
            params: this.$http.adornParams({
              currentPage: pageIndex,
              pageSize: pageSize,
            }),
          }).then(({ data }) => {
            // console.log(data.data.list[index]);
            this.dataForm = data.data.list[index];
            this.dataForm.organId = data.data.list[index].organId;
            this.dataForm.handsPersonId = data.data.list[index].handsPersonId;
            this.dataForm.id = id || 0;
          });
          this.$http({
            url: this.$http.adornUrl(`/accountItem/getDetailList`),
            method: "get",
            params: this.$http.adornParams({
              headerId: this.dataForm.id,
            }),
          }).then(({ data }) => {
            console.log(data.data.rows);
            if (data.data.rows.length == 0) {
              return;
            }
            this.dataList = data.data.rows[0];
            this.dataList.id = data.data.rows[0].Id;
          });
        } else {
          this.$http({
            url: this.$http.adornUrl("/depotHead/buildNumber"),
            method: "get",
          }).then(({ data }) => {
            // console.log(data);
            this.dataForm.billNo = "SR" + data.DefaultNumber;
          });
          // console.log(new Date());
          this.$set(this.dataForm, "billTime", new Date());
        }
      });

      // console.log(this.dataForm.id)
    },

    // 表单提交
    dataFormSubmit() {
      console.log(this.dataForm.id);
      let inServFormvalid = null;
      let dataFormvalid = null;
      console.log(this.dataForm.type);
      this.$refs["dataList"].validate((valid1) => {
        inServFormvalid = valid1;
      });
      this.$refs["dataForm"].validate((valid2) => {
        dataFormvalid = valid2;
      });
      if (inServFormvalid && dataFormvalid) {
        // console.log(this.dataForm.name);
        let info = {
          Type: "收入",
          BillNo: this.dataForm.billNo,
          BillTime: this.dataForm.billTime,
          AccountId: this.AccountId,
          ChangeAmount: this.dataList.EachAmount,
          TotalPrice: this.dataList.EachAmount,
          OrganId: this.OrganId,
          HandsPersonId: this.HandsPersonId,
          Remark: this.dataList.Remark,
        };
        // console.log(info)
        // let url = this.$http.adornUrl("/accountHead/add");
        // 编辑
        if (this.dataForm.id) {
          var url = this.$http.adornUrl(
            `/accountHead/update?id=${this.dataForm.id}`
          );
          let updated = [
            {
              AccountId: "",
              InOutItemId: this.InOutItemId,
              InOutItemName: this.dataList.InOutItemName,
              Id: this.dataList.id,
              EachAmount: this.dataList.EachAmount,
              AccountName: null,
              Remark: this.dataList.Remark,
            },
          ];
          this.$http({
            url,
            method: "post",
            data: this.$http.adornData(info, false),
          }).then(({ data }) => {
            console.log(data);
            this.$http({
              url: this.$http.adornUrl(`/accountItem/saveDetials`),
              method: "post",
              data: this.$http.adornData(
                {
                  inserted: [],
                  deleted: [],
                  updated,
                  headerId: this.dataForm.id,
                  listType: "收入",
                },
                false
              ),
            }).then((data) => {
              if (data.data && data.data.code === 0) {
                this.btnstatus = true;
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  },
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          });
        }
        // 增加
        else {
          var url = this.$http.adornUrl("/accountHead/add");
          let inserted = [
            {
              AccountId: "",
              InOutItemId: this.InOutItemId,
              InOutItemName: this.dataList.InOutItemName,
              EachAmount: this.dataList.EachAmount,
              Remark: this.dataList.Remark,
            },
          ];
          this.$http({
            url,
            method: "post",
            data: this.$http.adornData(info, false),
          }).then(({ data }) => {
            // console.log(data);
            this.$http({
              url: this.$http.adornUrl(`/accountHead/getMaxId`),
              method: "get",
            })
              .then((data) => {
                console.log(data);
                if (data.data && data.data.code === 0) {
                  this.id = data.data.maxId;
                  console.log(this.id);
                }
              })
              .then(() => {
                this.$http({
                  url: this.$http.adornUrl(`/accountItem/saveDetials`),
                  method: "post",
                  data: this.$http.adornData(
                    {
                      inserted,
                      deleted: [],
                      updated: [],
                      headerId: this.id,
                      listType: "收入",
                    },
                    false
                  ),
                }).then((data) => {
                  console.log(data);
                  if (data && data.data.code === 0) {
                    this.btnstatus = true;
                    this.$message({
                      message: "操作成功",
                      type: "success",
                      duration: 1500,
                      onClose: () => {
                        this.visible = false;
                        this.$emit("refreshDataList");
                      },
                    });
                  } else {
                    this.$message.error(data.msg);
                  }
                });
              });
          });
        }
      }
    },

    // 关闭 弹窗清空数据
    close() {
      this.dataForm.organId = "";
      this.dataForm.handsPersonId = "";
      this.dataForm.billTime = "";
      this.dataForm.billNo = "";
      this.dataList.InOutItemId = "";
      this.dataList.EachAmount = "";
      this.dataList.Remark = "";
      this.btnstatus = false;
    },
  },
};
</script>
